package com.letv.android.client.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;

import com.letv.android.young.client.R;
import com.letv.core.utils.LogInfo;
import com.letv.core.utils.UIsUtils;

import java.io.ByteArrayOutputStream;

/**
 * 圆形控件
 * 
 * @author ljnalex
 * 
 */
public class RoundImageView extends LetvImageView {

	/**
	 * 圆形直径
	 */
	private int diameter;
	/**
	 * 控件View的宽度与高度
	 */
	private int viewW, viewH, screenW;

	/**
	 * 圆控件的中心点坐标
	 */
	private int x, y;

	private Paint paint;

	private Bitmap bitmapFg;

	private Bitmap bitmapSrc;

	public RoundImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context, attrs);
	}

	private void init(Context context, AttributeSet attrs) {
		if (attrs != null) {
			TypedArray typedArr = context.obtainStyledAttributes(attrs,
					R.styleable.RoundImageView);
			diameter = typedArr.getDimensionPixelSize(
					R.styleable.RoundImageView_diameter, 0);
		}

		paint = new Paint();
		paint.setFilterBitmap(false);
		paint.setAntiAlias(true);
		paint.setStrokeWidth(2.0f);
		paint.setStyle(Style.STROKE);

		screenW = UIsUtils.getScreenWidth(context);
		diameter = UIsUtils.zoomWidth(context,diameter);
	}

	@SuppressLint("DrawAllocation")
	@Override
	protected void onDraw(Canvas canvas) {
		viewW = getWidth();
		viewH = getHeight();
		int minValue = viewW < viewH ? viewW : viewH;
		if (minValue > diameter) {
			x = (minValue - diameter) >> 1;
			y = (minValue - diameter) >> 1;
		} else {
			diameter = minValue;
		}

		Drawable drawable = getDrawable();
		if (drawable != null) {
			bitmapSrc = ((BitmapDrawable) drawable).getBitmap();
		}

		if (diameter != 0 && bitmapSrc != null) {
			bitmapFg = loadBitmap(bitmapSrc, diameter);
			Bitmap bitmap = getCircleBitmap(bitmapFg);
			canvas.drawBitmap(bitmap, x, y, paint);
		} else {
			super.onDraw(canvas);
		}
	}

	public void setDiameter(int diameter) {
		this.diameter = diameter;
	}

	/**
	 * 创建圆形位图
	 * 
	 * @param bitmap
	 * @return
	 */
	public Bitmap getCircleBitmap(Bitmap bitmap) {
		// 根据原始图片的宽、高，创建一个新的画布
		LogInfo.log("RoundImageView", "bitmap_width:" + bitmap.getWidth()
				+ "; bitmap_height:" + bitmap.getHeight());
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getWidth(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		// 根据原来图片大小画一个矩形
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());

		// 画笔
		final Paint paint = new Paint();
		paint.setAntiAlias(true);
		paint.setColor(getResources().getColor(R.color.letv_color_fff6f6f6));

		// 画出一个圆
		int radius = bitmap.getWidth() >> 1;
		canvas.drawCircle(radius, radius, radius, paint);

		// 取两层绘制交集,显示上层
		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);

		return output;
	}

	/**
	 * 图片裁剪
	 * 
	 * @param src
	 * @param w
	 * @return
	 */
	private Bitmap loadBitmap(Bitmap src, int w) {
		// 获得原始图片的宽高
		int width = src.getWidth();
		int height = src.getHeight();
		int offSetValue = 0;
		int minValue = width < height ? width : height;
		if (minValue >= 200) {
			offSetValue = 20;
		}

		LogInfo.log("RoundImageView", "src_width:" + width + "; src_height:"
				+ height);

		// 计算缩放比例
		float scaleWidth = ((float) w) / (width - offSetValue);
		float scaleHeight = ((float) w) / (height - offSetValue);

		// 取得想要缩放的matrix参数
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);

		// 得到新的图片
		bitmapSrc = Bitmap.createBitmap(src, offSetValue / 2, offSetValue / 2,
				width - offSetValue, height - offSetValue, matrix, true);

		return bitmapSrc;
	}

	public Bitmap decodeAbtoBm(byte[] b, int actualSize) {
		Bitmap bm; // prepare object to return

		// clear system and runtime of rubbish
		System.gc();
		Runtime.getRuntime().gc();

		// Decode image size only
		BitmapFactory.Options oo = new BitmapFactory.Options();
		// only decodes size, not the whole image
		// See Android documentation for more info.
		oo.inJustDecodeBounds = true;
		BitmapFactory.decodeByteArray(b, 0, b.length, oo);

		// The new size we want to scale to
		// final int REQUIRED_SIZE=200;

		// Important function to resize proportionally.
		// Find the correct scale value. It should be the power of 2.
		int scale = 1;
		while (oo.outWidth / scale / 2 >= actualSize
				&& oo.outHeight / scale / 2 >= actualSize)
			scale *= 2; // Actual scaler

		// Decode Options: byte array image with inSampleSize
		BitmapFactory.Options o2 = new BitmapFactory.Options();
		o2.inSampleSize = scale; // set scaler
		o2.inPurgeable = true; // for effeciency
		o2.inInputShareable = true;

		// Do actual decoding, this takes up resources and could crash
		// your com.ledim.app if you do not do it properly
		bm = BitmapFactory.decodeByteArray(b, 0, b.length, o2);

		// Just to be safe, clear system and runtime of rubbish again!
		System.gc();
		Runtime.getRuntime().gc();

		return bm; // return Bitmap to the method that called it
	}

	private byte[] Bitmap2Bytes(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}

}
